package com.my.ph.media.info;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.amilesend.mediainfo.MediaInfoBase;
import com.amilesend.mediainfo.lib.MediaInfoAccessor;
import com.amilesend.mediainfo.type.StreamType;
import lombok.Getter;

import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Optional;

@Getter
public class VideoMediaInfo extends MediaInfoBase<VideoMediaInfo> {

    public VideoMediaInfo(MediaInfoAccessor accessor) {
        super(accessor);
    }

    public List<String> getVideoCodecs() {
        String codecsList = getAccessor().get(StreamType.Video, 0, "Format");
        return parseList(codecsList);
    }

    public Duration getDuration() {
        long value = (long) Double.parseDouble(
                getAccessor().get(StreamType.General, 0, "Duration"));
        return Duration.ofMillis(value);
    }

    public int getWidth() {
        return Integer.parseInt(getAccessor().get(StreamType.Video, 0, "Width"));
    }

    public int getHeight() {
        return Integer.parseInt(getAccessor().get(StreamType.Video, 0, "Height"));
    }

    public Instant getCreationTime() {
        String encodingTime = getAccessor().get(StreamType.General, 0, "Encoded_Date");
        return parseTime(encodingTime);
    }

    public Double getFrameRate() {
        return Double.parseDouble(getAccessor().get(StreamType.Video, 0, "FrameRate"));
    }

    public String getBitDepth() {
        return getAccessor().get(StreamType.Video, 0, "BitDepth");
    }

    public String getAudioCodec() {
        return getAccessor().get(StreamType.Audio, 0, "Format");
    }

    public String getVideoCodec() {
        String format = getAccessor().get(StreamType.Video, 0, "Format");
        List<String> formatSplit = StrUtil.split(format, " ");
        return CollectionUtil.isEmpty(formatSplit) ? "" : formatSplit.get(0);
    }

    public String getHdrFormat() {
        String format = getAccessor().get(StreamType.Video, 0, "Format");
        List<String> formatSplit = StrUtil.split(format, " ");
        return CollectionUtil.isNotEmpty(formatSplit) && formatSplit.size() > 1 ? formatSplit.get(1) : "";
    }

    public Integer getChannels() {
        return Integer.parseInt(Optional.ofNullable(getAccessor().get(StreamType.Audio, 0, "Channel(s)"))
                .map(item -> StrUtil.isBlank(item) ? "2" : item)
                .orElse("2"));
    }

    public String getChannelLayout() {
        return getAccessor().get(StreamType.Audio, 0, "ChannelLayout");
    }

    public String getInform() {
        return getAccessor().inform();
    }
}
